import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;

public class StudentCourseSystem {

    // 系统核心数据存储
    private static Student[] students = new Student[100];
    private static Course[] courses = new Course[50];
    private static Enrollment[] enrollments = new Enrollment[500];

    // 数据计数器
    private static int studentCount = 0;
    private static int courseCount = 0;
    private static int enrollmentCount = 0;

    // 常量定义
    private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static void main(String[] args) {
        try (Scanner scanner = new Scanner(System.in)) {
            // 系统初始化
            initializeSystem();

            // 显示主菜单
            mainMenu(scanner);
        }
    }

    // 系统初始化
    private static void initializeSystem() {
        System.out.println("=== 学生选课管理系统 ===");
        System.out.println("正在初始化系统...");

        // 加载初始数据
        loadInitialData();

        System.out.println("系统初始化完成！");
        System.out.println("当前学生数: " + studentCount);
        System.out.println("当前课程数: " + courseCount);
        System.out.println("当前选课记录数: " + enrollmentCount);
        System.out.println("=======================\n");
    }

    // 加载初始数据
    private static void loadInitialData() {
        // 添加初始学生
        students[studentCount++] = new Student("2023001", "张三", "男", 20, "计算机2301班");
        students[studentCount++] = new Student("2023002", "李四", "女", 19, "计算机2301班");
        students[studentCount++] = new Student("2023003", "王五", "男", 20, "软件2302班");

        // 添加初始课程
        courses[courseCount++] = new Course("C001", "Java程序设计", 3, "李老师", "周一3-4节", "计算机楼201", 40);
        courses[courseCount++] = new Course("C002", "数据结构", 4, "王老师", "周二1-2节", "计算机楼302", 35);
        courses[courseCount++] = new Course("C003", "数据库原理", 3, "张老师", "周三5-6节", "计算机楼105", 45);

        // 添加初始选课记录
        enrollments[enrollmentCount++] = new Enrollment("2023001", "C001", "2023-09-01");
        enrollments[enrollmentCount++] = new Enrollment("2023001", "C002", "2023-09-01");
        enrollments[enrollmentCount++] = new Enrollment("2023002", "C001", "2023-09-02");
        enrollments[enrollmentCount++] = new Enrollment("2023003", "C003", "2023-09-02");
    }

    // 主菜单
    private static void mainMenu(Scanner scanner) {
        while (true) {
            System.out.println("\n=== 主菜单 ===");
            System.out.println("1. 学生信息管理");
            System.out.println("2. 课程信息管理");
            System.out.println("3. 选课操作");
            System.out.println("4. 成绩管理");
            System.out.println("5. 数据查询");
            System.out.println("6. 数据统计");
            System.out.println("0. 退出系统");
            System.out.print("请选择功能(0-6): ");

            int choice = scanner.nextInt();
            scanner.nextLine(); // consume the newline

            switch (choice) {
                case 1:
                    studentManagementMenu(scanner);
                    break;
                case 2:
                    courseManagementMenu(scanner);
                    break;
                case 3:
                    enrollmentMenu(scanner);
                    break;
                case 4:
                    gradeManagementMenu(scanner);
                    break;
                case 5:
                    queryMenu(scanner);
                    break;
                case 6:
                    statisticsMenu(scanner);
                    break;
                case 0:
                    System.out.println("感谢使用，再见！");
                    return;
                default:
                    System.out.println("无效的选择，请重新输入！");
            }
        }
    }

    // 学生信息管理子菜单

    private static void studentManagementMenu(Scanner scanner) {
        System.out.println("\n=== 学生信息管理 ===");
        System.out.println("1. 添加学生");
        System.out.println("2. 修改学生信息");
        System.out.println("3. 删除学生");
        System.out.println("4. 查询学生信息");
        System.out.println("0. 返回主菜单");
        System.out.print("请选择功能(0-4): ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                addStudent(scanner);
                break;
            case 2:
                modifyStudent(scanner);
                break;
            case 3:
                deleteStudent(scanner);
                break;
            case 4:
                queryStudent(scanner);
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 课程信息管理子菜单
    private static void courseManagementMenu(Scanner scanner) {
        System.out.println("\n=== 课程信息管理 ===");
        System.out.println("1. 添加课程");
        System.out.println("2. 修改课程信息");
        System.out.println("3. 删除课程");
        System.out.println("4. 查询课程信息");
        System.out.println("0. 返回主菜单");
        System.out.print("请选择功能(0-4): ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                addCourse(scanner);
                break;
            case 2:
                modifyCourse(scanner);
                break;
            case 3:
                deleteCourse(scanner);
                break;
            case 4:
                queryCourse(scanner);
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 选课操作子菜单
    private static void enrollmentMenu(Scanner scanner) {
        System.out.println("\n=== 选课操作 ===");
        System.out.println("1. 学生选课");
        System.out.println("2. 学生退课");
        System.out.println("3. 查询学生选课情况");
        System.out.println("0. 返回主菜单");
        System.out.print("请选择功能(0-3): ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                studentEnrollCourse(scanner);
                break;
            case 2:
                studentDropCourse(scanner);
                break;
            case 3:
                queryStudentEnrollments(scanner);
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 成绩管理子菜单
    private static void gradeManagementMenu(Scanner scanner) {
        System.out.println("\n=== 成绩管理 ===");
        System.out.println("1. 录入成绩");
        System.out.println("2. 修改成绩");
        System.out.println("3. 查询成绩");
        System.out.println("0. 返回主菜单");
        System.out.print("请选择功能(0-3): ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                inputGrade(scanner);
                break;
            case 2:
                modifyGrade(scanner);
                break;
            case 3:
                queryGrade(scanner);
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 数据查询子菜单
    private static void queryMenu(Scanner scanner) {
        System.out.println("\n=== 数据查询 ===");
        System.out.println("1. 查询所有学生");
        System.out.println("2. 查询所有课程");
        System.out.println("3. 按班级查询学生");
        System.out.println("4. 按教师查询课程");
        System.out.println("0. 返回主菜单");
        System.out.print("请选择功能(0-4): ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                queryAllStudents();
                break;
            case 2:
                queryAllCourses();
                break;
            case 3:
                queryStudentsByClass(scanner);
                break;
            case 4:
                queryCoursesByTeacher(scanner);
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 数据统计子菜单
    private static void statisticsMenu(Scanner scanner) {
        System.out.println("\n=== 数据统计 ===");
        System.out.println("1. 统计每门课程选课人数");
        System.out.println("2. 统计每个学生选课门数");
        System.out.println("3. 统计课程成绩分布");
        System.out.println("0. 返回主菜单");
        System.out.print("请选择功能(0-3): ");

        int choice = scanner.nextInt();
        scanner.nextLine();

        switch (choice) {
            case 1:
                countEnrollmentsPerCourse();
                break;
            case 2:
                countCoursesPerStudent();
                break;
            case 3:
                analyzeGradeDistribution();
                break;
            case 0:
                return;
            default:
                System.out.println("无效的选择，请重新输入！");
        }
    }

    // 提取公共方法：通过学号查找学生索引
    private static int findStudentIndexById(String studentId) {
        for (int i = 0; i < studentCount; i++) {
            if (students[i].getStudentId().equals(studentId)) {
                return i;
            }
        }
        return -1;
    }

    // 添加学生
    private static void addStudent(Scanner scanner) {
        System.out.println("\n=== 添加学生 ===");

        System.out.print("请输入学号: ");
        String studentId = scanner.nextLine().trim();
        if (studentId.isEmpty()) {
            System.out.println("错误：学号不能为空！");
            return;
        }

        // 检查学号是否已存在
        if (findStudentIndexById(studentId) != -1) {
            System.out.println("错误：学号已存在！");
            return;
        }

        System.out.print("请输入姓名: ");
        String name = scanner.nextLine().trim();
        if (name.isEmpty()) {
            System.out.println("错误：姓名不能为空！");
            return;
        }

        System.out.print("请输入性别(男/女): ");
        String gender = scanner.nextLine().trim();
        if (!gender.equals("男") && !gender.equals("女")) {
            System.out.println("错误：性别只能是'男'或'女'！");
            return;
        }

        System.out.print("请输入年龄: ");
        int age;
        try {
            age = Integer.parseInt(scanner.nextLine().trim());
            if (age <= 0 || age > 150) {
                System.out.println("错误：年龄必须在1-150之间！");
                return;
            }
        } catch (NumberFormatException e) {
            System.out.println("错误：年龄必须是数字！");
            return;
        }

        System.out.print("请输入班级: ");
        String className = scanner.nextLine().trim();
        if (className.isEmpty()) {
            System.out.println("错误：班级不能为空！");
            return;
        }

        // 检查学生数组是否需要扩容
        if (studentCount >= students.length) {
            Student[] newStudents = new Student[students.length * 2];
            System.arraycopy(students, 0, newStudents, 0, students.length);
            students = newStudents;
        }

        students[studentCount] = new Student(studentId, name, gender, age, className);
        studentCount++;

        System.out.println("学生添加成功！");
    }

    // 修改学生信息
    private static void modifyStudent(Scanner scanner) {
        System.out.println("\n=== 修改学生信息 ===");

        System.out.print("请输入要修改的学生学号: ");
        String studentId = scanner.nextLine().trim();
        if (studentId.isEmpty()) {
            System.out.println("错误：学号不能为空！");
            return;
        }

        int studentIndex = findStudentIndexById(studentId);
        if (studentIndex == -1) {
            System.out.println("错误：学号不存在！");
            return;
        }

        Student student = students[studentIndex];
        System.out.println("当前学生信息:");
        System.out.println("学号: " + student.getStudentId());
        System.out.println("姓名: " + student.getName());
        System.out.println("性别: " + student.getGender());
        System.out.println("年龄: " + student.getAge());
        System.out.println("班级: " + student.getClassName());

        System.out.println("\n请输入新的信息(回车跳过不修改):");

        System.out.print("姓名 [" + student.getName() + "]: ");
        String name = scanner.nextLine().trim();
        if (!name.isEmpty()) {
            student.setName(name);
        }

        System.out.print("性别 [" + student.getGender() + "]: ");
        String gender = scanner.nextLine().trim();
        if (!gender.isEmpty()) {
            if (gender.equals("男") || gender.equals("女")) {
                student.setGender(gender);
            } else {
                System.out.println("警告：性别只能是'男'或'女'，未修改性别！");
            }
        }

        System.out.print("年龄 [" + student.getAge() + "]: ");
        String ageStr = scanner.nextLine().trim();
        if (!ageStr.isEmpty()) {
            try {
                int age = Integer.parseInt(ageStr);
                if (age > 0 && age <= 150) {
                    student.setAge(age);
                } else {
                    System.out.println("警告：年龄必须在1-150之间，未修改年龄！");
                }
            } catch (NumberFormatException e) {
                System.out.println("警告：年龄必须是数字，未修改年龄！");
            }
        }

        System.out.print("班级 [" + student.getClassName() + "]: ");
        String className = scanner.nextLine().trim();
        if (!className.isEmpty()) {
            student.setClassName(className);
        }

        System.out.println("学生信息修改成功！");
    }

    // 删除学生
    private static void deleteStudent(Scanner scanner) {
        System.out.println("\n=== 删除学生 ===");

        System.out.print("请输入要删除的学生学号: ");
        String studentId = scanner.nextLine().trim();
        if (studentId.isEmpty()) {
            System.out.println("错误：学号不能为空！");
            return;
        }

        int studentIndex = findStudentIndexById(studentId);
        if (studentIndex == -1) {
            System.out.println("错误：学号不存在！");
            return;
        }

        // 确认删除
        System.out.print("确认删除学生 " + students[studentIndex].getName() + " 吗？(y/n): ");
        String confirm = scanner.nextLine().trim();
        if (!confirm.equalsIgnoreCase("y") && !confirm.equalsIgnoreCase("yes")) {
            System.out.println("取消删除操作。");
            return;
        }

        // 删除相关的选课记录
        int deletedEnrollments = 0;
        for (int i = enrollmentCount - 1; i >= 0; i--) {
            if (enrollments[i].getStudentId().equals(studentId)) {
                // 将后续元素前移
                for (int j = i; j < enrollmentCount - 1; j++) {
                    enrollments[j] = enrollments[j + 1];
                }
                enrollmentCount--;
                deletedEnrollments++;
            }
        }

        // 将后续学生前移
        for (int i = studentIndex; i < studentCount - 1; i++) {
            students[i] = students[i + 1];
        }
        studentCount--;

        System.out.println("学生删除成功！共删除 " + deletedEnrollments + " 条选课记录。");
    }

    // 查询学生信息
    private static void queryStudent(Scanner scanner) {
        System.out.println("\n=== 查询学生信息 ===");

        System.out.print("请输入要查询的学生学号: ");
        String studentId = scanner.nextLine().trim();
        if (studentId.isEmpty()) {
            System.out.println("错误：学号不能为空！");
            return;
        }

        int studentIndex = findStudentIndexById(studentId);
        if (studentIndex == -1) {
            System.out.println("错误：学号不存在！");
            return;
        }

        Student student = students[studentIndex];
        System.out.println("学生信息:");
        System.out.println("学号: " + student.getStudentId());
        System.out.println("姓名: " + student.getName());
        System.out.println("性别: " + student.getGender());
        System.out.println("年龄: " + student.getAge());
        System.out.println("班级: " + student.getClassName());
    }

    // 学生选课
    private static void studentEnrollCourse(Scanner scanner) {
        System.out.println("\n=== 学生选课 ===");

        // 输入学号和课程号
        System.out.print("请输入学号: ");
        String studentId = scanner.nextLine().trim();
        if (studentId.isEmpty()) {
            System.out.println("错误：学号不能为空！");
            return;
        }

        System.out.print("请输入课程号: ");
        String courseId = scanner.nextLine().trim();
        if (courseId.isEmpty()) {
            System.out.println("错误：课程号不能为空！");
            return;
        }

        // 1. 验证学号是否存在
        int studentIndex = findStudentIndexById(studentId);
        if (studentIndex == -1) {
            System.out.println("错误：学号不存在！");
            return;
        }

        // 2. 验证课程号是否存在
        int courseIndex = -1;
        for (int i = 0; i < courseCount; i++) {
            if (courses[i].getCourseId().equals(courseId)) {
                courseIndex = i;
                break;
            }
        }

        if (courseIndex == -1) {
            System.out.println("错误：课程号不存在！");
            return;
        }

        // 3. 检查是否已选该课程
        for (int i = 0; i < enrollmentCount; i++) {
            if (enrollments[i].getStudentId().equals(studentId) &&
                    enrollments[i].getCourseId().equals(courseId)) {
                System.out.println("错误：该学生已选此课程！");
                return;
            }
        }

        // 4. 检查课程容量是否已满
        if (courses[courseIndex].getEnrolledCount() >= courses[courseIndex].getCapacity()) {
            System.out.println("错误：该课程已满，无法选课！");
            return;
        }

        // 5. 检查选课记录数组是否已满，如需扩容
        if (enrollmentCount >= enrollments.length) {
            System.out.println("选课记录数组已满，正在扩容...");
            Enrollment[] newEnrollments = new Enrollment[enrollments.length * 2];
            System.arraycopy(enrollments, 0, newEnrollments, 0, enrollments.length);
            enrollments = newEnrollments;
        }

        // 6. 创建选课记录
        String currentDate = LocalDate.now().format(DATE_FORMATTER);
        enrollments[enrollmentCount] = new Enrollment(studentId, courseId, currentDate);
        enrollmentCount++;

        // 7. 更新课程选课人数
        courses[courseIndex].incrementEnrolledCount();

        System.out.println("选课成功！");
        System.out.println("学生: " + students[studentIndex].getName() + "(" + studentId + ")");
        System.out.println("课程: " + courses[courseIndex].getCourseName() + "(" + courseId + ")");
        System.out.println("选课日期: " + currentDate);
    }

    // 以下是各个功能的空实现，需要你根据设计逐步完善

   private static void addCourse(Scanner scanner) {
    System.out.println("\n=== 添加课程 ===");

    System.out.print("请输入课程编号: ");
    String courseId = scanner.nextLine().trim();
    if (courseId.isEmpty()) {
        System.out.println("错误：课程编号不能为空！");
        return;
    }

    // 检查课程编号是否已存在
    for (int i = 0; i < courseCount; i++) {
        if (courses[i].getCourseId().equals(courseId)) {
            System.out.println("错误：课程编号已存在！");
            return;
        }
    }

    System.out.print("请输入课程名称: ");
    String courseName = scanner.nextLine().trim();
    if (courseName.isEmpty()) {
        System.out.println("错误：课程名称不能为空！");
        return;
    }

    System.out.print("请输入学分: ");
    int credit;
    try {
        credit = Integer.parseInt(scanner.nextLine().trim());
        if (credit <= 0) {
            System.out.println("错误：学分必须大于0！");
            return;
        }
    } catch (NumberFormatException e) {
        System.out.println("错误：学分必须是数字！");
        return;
    }

    System.out.print("请输入授课教师: ");
    String teacher = scanner.nextLine().trim();
    if (teacher.isEmpty()) {
        System.out.println("错误：授课教师不能为空！");
        return;
    }

    System.out.print("请输入上课时间: ");
    String time = scanner.nextLine().trim();
    if (time.isEmpty()) {
        System.out.println("错误：上课时间不能为空！");
        return;
    }

    System.out.print("请输入上课教室: ");
    String classroom = scanner.nextLine().trim();
    if (classroom.isEmpty()) {
        System.out.println("错误：上课教室不能为空！");
        return;
    }

    System.out.print("请输入课程容量: ");
    int capacity;
    try {
        capacity = Integer.parseInt(scanner.nextLine().trim());
        if (capacity <= 0) {
            System.out.println("错误：课程容量必须大于0！");
            return;
        }
    } catch (NumberFormatException e) {
        System.out.println("错误：课程容量必须是数字！");
        return;
    }

    // 检查课程数组是否需要扩容
    if (courseCount >= courses.length) {
        Course[] newCourses = new Course[courses.length * 2];
        System.arraycopy(courses, 0, newCourses, 0, courses.length);
        courses = newCourses;
    }

    courses[courseCount] = new Course(courseId, courseName, credit, teacher, time, classroom, capacity);
    courseCount++;

    System.out.println("课程添加成功！");
}

private static int findCourseIndexById(String courseId) {
    for (int i = 0; i < courseCount; i++) {
        if (courses[i].getCourseId().equals(courseId)) {
            return i;
        }
    }
    return -1;
}

private static void modifyCourse(Scanner scanner) {
    System.out.println("\n=== 修改课程信息 ===");

    System.out.print("请输入要修改的课程编号: ");
    String courseId = scanner.nextLine().trim();
    if (courseId.isEmpty()) {
        System.out.println("错误：课程编号不能为空！");
        return;
    }

    int courseIndex = findCourseIndexById(courseId);
    if (courseIndex == -1) {
        System.out.println("错误：课程编号不存在！");
        return;
    }

    Course course = courses[courseIndex];
    System.out.println("当前课程信息:");
    System.out.println(course.toString());

    System.out.println("\n请输入新的信息(回车跳过不修改):");

    System.out.print("课程名称 [" + course.getCourseName() + "]: ");
    String courseName = scanner.nextLine().trim();
    if (!courseName.isEmpty()) {
        course.setCourseName(courseName);
    }

    System.out.print("学分 [" + course.getCredit() + "]: ");
    String creditStr = scanner.nextLine().trim();
    if (!creditStr.isEmpty()) {
        try {
            int credit = Integer.parseInt(creditStr);
            if (credit > 0) {
                course.setCredit(credit);
            } else {
                System.out.println("警告：学分必须大于0，未修改学分！");
            }
        } catch (NumberFormatException e) {
            System.out.println("警告：学分必须是数字，未修改学分！");
        }
    }

    System.out.print("授课教师 [" + course.getTeacher() + "]: ");
    String teacher = scanner.nextLine().trim();
    if (!teacher.isEmpty()) {
        course.setTeacher(teacher);
    }

    System.out.print("上课时间 [" + course.getTime() + "]: ");
    String time = scanner.nextLine().trim();
    if (!time.isEmpty()) {
        course.setTime(time);
    }

    System.out.print("上课教室 [" + course.getClassroom() + "]: ");
    String classroom = scanner.nextLine().trim();
    if (!classroom.isEmpty()) {
        course.setClassroom(classroom);
    }

    System.out.print("课程容量 [" + course.getCapacity() + "]: ");
    String capacityStr = scanner.nextLine().trim();
    if (!capacityStr.isEmpty()) {
        try {
            int capacity = Integer.parseInt(capacityStr);
            if (capacity > 0) {
                // 如果新容量小于当前选课人数，需要提示用户
                if (capacity < course.getEnrolledCount()) {
                    System.out.println("警告：新容量小于当前选课人数(" + course.getEnrolledCount() + ")，请谨慎修改！");
                    System.out.print("是否继续修改容量？(y/n): ");
                    String confirm = scanner.nextLine().trim();
                    if (!confirm.equalsIgnoreCase("y") && !confirm.equalsIgnoreCase("yes")) {
                        System.out.println("取消修改容量。");
                        return;
                    }
                }
                course.setCapacity(capacity);
            } else {
                System.out.println("警告：课程容量必须大于0，未修改容量！");
            }
        } catch (NumberFormatException e) {
            System.out.println("警告：课程容量必须是数字，未修改容量！");
        }
    }

    System.out.println("课程信息修改成功！");
}

private static void deleteCourse(Scanner scanner) {
    System.out.println("\n=== 删除课程 ===");

    System.out.print("请输入要删除的课程编号: ");
    String courseId = scanner.nextLine().trim();
    if (courseId.isEmpty()) {
        System.out.println("错误：课程编号不能为空！");
        return;
    }

    int courseIndex = findCourseIndexById(courseId);
    if (courseIndex == -1) {
        System.out.println("错误：课程编号不存在！");
        return;
    }

    // 确认删除
    System.out.print("确认删除课程 " + courses[courseIndex].getCourseName() + " 吗？(y/n): ");
    String confirm = scanner.nextLine().trim();
    if (!confirm.equalsIgnoreCase("y") && !confirm.equalsIgnoreCase("yes")) {
        System.out.println("取消删除操作。");
        return;
    }

    // 删除相关的选课记录
    int deletedEnrollments = 0;
    for (int i = enrollmentCount - 1; i >= 0; i--) {
        if (enrollments[i].getCourseId().equals(courseId)) {
            // 将后续元素前移
            for (int j = i; j < enrollmentCount - 1; j++) {
                enrollments[j] = enrollments[j + 1];
            }
            enrollmentCount--;
            deletedEnrollments++;
        }
    }

    // 将后续课程前移
    for (int i = courseIndex; i < courseCount - 1; i++) {
        courses[i] = courses[i + 1];
    }
    courseCount--;

    System.out.println("课程删除成功！共删除 " + deletedEnrollments + " 条选课记录。");
}

private static void queryCourse(Scanner scanner) {
    System.out.println("\n=== 查询课程信息 ===");

    System.out.print("请输入要查询的课程编号: ");
    String courseId = scanner.nextLine().trim();
    if (courseId.isEmpty()) {
        System.out.println("错误：课程编号不能为空！");
        return;
    }

    int courseIndex = findCourseIndexById(courseId);
    if (courseIndex == -1) {
        System.out.println("错误：课程编号不存在！");
        return;
    }

    Course course = courses[courseIndex];
    System.out.println("课程信息:");
    System.out.println(course.toString());
}

   private static void studentDropCourse(Scanner scanner) {
    System.out.println("\n=== 学生退课 ===");

    // 输入学号和课程号
    System.out.print("请输入学号: ");
    String studentId = scanner.nextLine().trim();
    if (studentId.isEmpty()) {
        System.out.println("错误：学号不能为空！");
        return;
    }

    System.out.print("请输入课程号: ");
    String courseId = scanner.nextLine().trim();
    if (courseId.isEmpty()) {
        System.out.println("错误：课程号不能为空！");
        return;
    }

    // 1. 验证学号是否存在
    int studentIndex = findStudentIndexById(studentId);
    if (studentIndex == -1) {
        System.out.println("错误：学号不存在！");
        return;
    }

    // 2. 验证课程号是否存在
    int courseIndex = findCourseIndexById(courseId);
    if (courseIndex == -1) {
        System.out.println("错误：课程号不存在！");
        return;
    }

    // 3. 检查是否已选该课程
    int enrollmentIndex = -1;
    for (int i = 0; i < enrollmentCount; i++) {
        if (enrollments[i].getStudentId().equals(studentId) &&
                enrollments[i].getCourseId().equals(courseId)) {
            enrollmentIndex = i;
            break;
        }
    }

    if (enrollmentIndex == -1) {
        System.out.println("错误：该学生未选此课程！");
        return;
    }

    // 4. 确认退课操作
    System.out.print("确认退课 " + courses[courseIndex].getCourseName() + " 吗？(y/n): ");
    String confirm = scanner.nextLine().trim();
    if (!confirm.equalsIgnoreCase("y") && !confirm.equalsIgnoreCase("yes")) {
        System.out.println("取消退课操作。");
        return;
    }

    // 5. 删除选课记录
    for (int i = enrollmentIndex; i < enrollmentCount - 1; i++) {
        enrollments[i] = enrollments[i + 1];
    }
    enrollmentCount--;

    // 6. 更新课程选课人数
    courses[courseIndex].decrementEnrolledCount();

    System.out.println("退课成功！");
    System.out.println("学生: " + students[studentIndex].getName() + "(" + studentId + ")");
    System.out.println("课程: " + courses[courseIndex].getCourseName() + "(" + courseId + ")");
}


   private static void queryStudentEnrollments(Scanner scanner) {
    System.out.println("\n=== 查询学生选课情况 ===");

    System.out.print("请输入学生学号: ");
    String studentId = scanner.nextLine().trim();
    if (studentId.isEmpty()) {
        System.out.println("错误：学号不能为空！");
        return;
    }

    // 验证学号是否存在
    int studentIndex = findStudentIndexById(studentId);
    if (studentIndex == -1) {
        System.out.println("错误：学号不存在！");
        return;
    }

    Student student = students[studentIndex];
    System.out.println("学生信息: " + student.getName() + "(" + studentId + ")");
    System.out.println("选课情况如下:");

    boolean hasEnrollments = false;
    int courseCounter = 1;

    // 遍历所有选课记录，找到该学生的选课信息
    for (int i = 0; i < enrollmentCount; i++) {
        if (enrollments[i].getStudentId().equals(studentId)) {
            hasEnrollments = true;
            String courseId = enrollments[i].getCourseId();

            // 查找对应的课程信息
            int courseIndex = findCourseIndexById(courseId);
            if (courseIndex != -1) {
                Course course = courses[courseIndex];
                System.out.println(courseCounter + ". " + course.toString());
                System.out.println("   选课日期: " + enrollments[i].getEnrollmentDate());
            }
            courseCounter++;
        }
    }

    if (!hasEnrollments) {
        System.out.println("该学生暂未选课。");
    } else {
        System.out.println("共选课 " + (courseCounter - 1) + " 门。");
    }
}

    private static void inputGrade(Scanner scanner) {
    System.out.println("\n=== 录入成绩 ===");

    // 输入学号和课程号
    System.out.print("请输入学号: ");
    String studentId = scanner.nextLine().trim();
    if (studentId.isEmpty()) {
        System.out.println("错误：学号不能为空！");
        return;
    }

    System.out.print("请输入课程号: ");
    String courseId = scanner.nextLine().trim();
    if (courseId.isEmpty()) {
        System.out.println("错误：课程号不能为空！");
        return;
    }

    // 1. 验证学号是否存在
    int studentIndex = findStudentIndexById(studentId);
    if (studentIndex == -1) {
        System.out.println("错误：学号不存在！");
        return;
    }

    // 2. 验证课程号是否存在
    int courseIndex = findCourseIndexById(courseId);
    if (courseIndex == -1) {
        System.out.println("错误：课程号不存在！");
        return;
    }

    // 3. 检查学生是否已选该课程
    int enrollmentIndex = -1;
    for (int i = 0; i < enrollmentCount; i++) {
        if (enrollments[i].getStudentId().equals(studentId) &&
            enrollments[i].getCourseId().equals(courseId)) {
            enrollmentIndex = i;
            break;
        }
    }

    if (enrollmentIndex == -1) {
        System.out.println("错误：该学生未选此课程，无法录入成绩！");
        return;
    }

    // 4. 检查是否已录入过成绩
    if (enrollments[enrollmentIndex].getGrade() != null) {
        System.out.println("错误：该课程成绩已录入，请使用修改成绩功能！");
        return;
    }

    // 5. 输入成绩
    System.out.print("请输入成绩(0-100): ");
    double grade;
    try {
        grade = Double.parseDouble(scanner.nextLine().trim());
        if (grade < 0 || grade > 100) {
            System.out.println("错误：成绩必须在0-100之间！");
            return;
        }
    } catch (NumberFormatException e) {
        System.out.println("错误：成绩必须是数字！");
        return;
    }

    // 6. 录入成绩
    enrollments[enrollmentIndex].setGrade(grade);

    System.out.println("成绩录入成功！");
    System.out.println("学生: " + students[studentIndex].getName() + "(" + studentId + ")");
    System.out.println("课程: " + courses[courseIndex].getCourseName() + "(" + courseId + ")");
    System.out.println("成绩: " + grade);
}

private static void modifyGrade(Scanner scanner) {
    System.out.println("\n=== 修改成绩 ===");

    // 输入学号和课程号
    System.out.print("请输入学号: ");
    String studentId = scanner.nextLine().trim();
    if (studentId.isEmpty()) {
        System.out.println("错误：学号不能为空！");
        return;
    }

    System.out.print("请输入课程号: ");
    String courseId = scanner.nextLine().trim();
    if (courseId.isEmpty()) {
        System.out.println("错误：课程号不能为空！");
        return;
    }

    // 1. 验证学号是否存在
    int studentIndex = findStudentIndexById(studentId);
    if (studentIndex == -1) {
        System.out.println("错误：学号不存在！");
        return;
    }

    // 2. 验证课程号是否存在
    int courseIndex = findCourseIndexById(courseId);
    if (courseIndex == -1) {
        System.out.println("错误：课程号不存在！");
        return;
    }

    // 3. 检查学生是否已选该课程
    int enrollmentIndex = -1;
    for (int i = 0; i < enrollmentCount; i++) {
        if (enrollments[i].getStudentId().equals(studentId) &&
            enrollments[i].getCourseId().equals(courseId)) {
            enrollmentIndex = i;
            break;
        }
    }

    if (enrollmentIndex == -1) {
        System.out.println("错误：该学生未选此课程！");
        return;
    }

    // 4. 检查是否已录入过成绩
    Double currentGrade = enrollments[enrollmentIndex].getGrade();
    if (currentGrade == null) {
        System.out.println("错误：该课程尚未录入成绩，请使用录入成绩功能！");
        return;
    }

    // 5. 显示当前成绩
    System.out.println("当前成绩: " + currentGrade);

    // 6. 输入新成绩
    System.out.print("请输入新成绩(0-100): ");
    double newGrade;
    try {
        newGrade = Double.parseDouble(scanner.nextLine().trim());
        if (newGrade < 0 || newGrade > 100) {
            System.out.println("错误：成绩必须在0-100之间！");
            return;
        }
    } catch (NumberFormatException e) {
        System.out.println("错误：成绩必须是数字！");
        return;
    }

    // 7. 确认修改
    System.out.print("确认将成绩从 " + currentGrade + " 修改为 " + newGrade + " 吗？(y/n): ");
    String confirm = scanner.nextLine().trim();
    if (!confirm.equalsIgnoreCase("y") && !confirm.equalsIgnoreCase("yes")) {
        System.out.println("取消修改操作。");
        return;
    }

    // 8. 修改成绩
    enrollments[enrollmentIndex].setGrade(newGrade);

    System.out.println("成绩修改成功！");
    System.out.println("学生: " + students[studentIndex].getName() + "(" + studentId + ")");
    System.out.println("课程: " + courses[courseIndex].getCourseName() + "(" + courseId + ")");
    System.out.println("原成绩: " + currentGrade + " -> 新成绩: " + newGrade);
}

private static void queryGrade(Scanner scanner) {
    System.out.println("\n=== 查询成绩 ===");

    System.out.print("请输入学生学号: ");
    String studentId = scanner.nextLine().trim();
    if (studentId.isEmpty()) {
        System.out.println("错误：学号不能为空！");
        return;
    }

    // 验证学号是否存在
    int studentIndex = findStudentIndexById(studentId);
    if (studentIndex == -1) {
        System.out.println("错误：学号不存在！");
        return;
    }

    Student student = students[studentIndex];
    System.out.println("学生信息: " + student.getName() + "(" + studentId + ")");
    System.out.println("成绩信息如下:");

    boolean hasGrades = false;
    int courseCounter = 1;
    double totalGrade = 0;
    int gradedCourses = 0;

    // 遍历所有选课记录，找到该学生的成绩信息
    for (int i = 0; i < enrollmentCount; i++) {
        if (enrollments[i].getStudentId().equals(studentId)) {
            String courseId = enrollments[i].getCourseId();

            // 查找对应的课程信息
            int courseIndex = findCourseIndexById(courseId);
            if (courseIndex != -1) {
                Course course = courses[courseIndex];
                Double grade = enrollments[i].getGrade();

                System.out.print(courseCounter + ". " + course.getCourseName() + "(" + courseId + ")");

                if (grade != null) {
                    System.out.println(" - 成绩: " + grade);
                    totalGrade += grade;
                    gradedCourses++;
                    hasGrades = true;
                } else {
                    System.out.println(" - 成绩: 未录入");
                }
                courseCounter++;
            }
        }
    }

    if (!hasGrades) {
        System.out.println("该学生暂无成绩记录。");
    } else {
        double averageGrade = totalGrade / gradedCourses;
        System.out.println("平均成绩: " + String.format("%.2f", averageGrade));
        System.out.println("已录入成绩课程数: " + gradedCourses + "/" + (courseCounter - 1));
    }
}

   private static void queryAllStudents() {
    System.out.println("\n=== 所有学生信息 ===");
    if (studentCount == 0) {
        System.out.println("暂无学生信息。");
        return;
    }

    System.out.println("共有 " + studentCount + " 名学生：");
    for (int i = 0; i < studentCount; i++) {
        System.out.println((i + 1) + ". " + students[i].toString());
    }
}

private static void queryAllCourses() {
    System.out.println("\n=== 所有课程信息 ===");
    if (courseCount == 0) {
        System.out.println("暂无课程信息。");
        return;
    }

    System.out.println("共有 " + courseCount + " 门课程：");
    for (int i = 0; i < courseCount; i++) {
        System.out.println((i + 1) + ". " + courses[i].toString());
    }
}

private static void queryStudentsByClass(Scanner scanner) {
    System.out.println("\n=== 按班级查询学生 ===");
    System.out.print("请输入班级名称: ");
    String className = scanner.nextLine().trim();
    if (className.isEmpty()) {
        System.out.println("错误：班级名称不能为空！");
        return;
    }

    System.out.println("班级 \"" + className + "\" 的学生信息：");
    boolean found = false;
    int count = 0;

    for (int i = 0; i < studentCount; i++) {
        if (students[i].getClassName().equals(className)) {
            System.out.println((count + 1) + ". " + students[i].toString());
            found = true;
            count++;
        }
    }

    if (!found) {
        System.out.println("未找到该班级的学生。");
    } else {
        System.out.println("共找到 " + count + " 名学生。");
    }
}

private static void queryCoursesByTeacher(Scanner scanner) {
    System.out.println("\n=== 按教师查询课程 ===");
    System.out.print("请输入教师姓名: ");
    String teacher = scanner.nextLine().trim();
    if (teacher.isEmpty()) {
        System.out.println("错误：教师姓名不能为空！");
        return;
    }

    System.out.println("教师 \"" + teacher + "\" 的课程信息：");
    boolean found = false;
    int count = 0;

    for (int i = 0; i < courseCount; i++) {
        if (courses[i].getTeacher().equals(teacher)) {
            System.out.println((count + 1) + ". " + courses[i].toString());
            found = true;
            count++;
        }
    }

    if (!found) {
        System.out.println("未找到该教师的课程。");
    } else {
        System.out.println("共找到 " + count + " 门课程。");
    }
}

   private static void countEnrollmentsPerCourse() {
    System.out.println("\n=== 每门课程选课人数统计 ===");
    if (courseCount == 0) {
        System.out.println("暂无课程信息。");
        return;
    }

    System.out.println("课程选课人数统计结果：");
    for (int i = 0; i < courseCount; i++) {
        Course course = courses[i];
        System.out.println((i + 1) + ". " + course.getCourseName() +
                          "(" + course.getCourseId() + ")" +
                          " - 选课人数: " + course.getEnrolledCount() +
                          "/" + course.getCapacity());
    }
}

private static void countCoursesPerStudent() {
    System.out.println("\n=== 每个学生选课门数统计 ===");
    if (studentCount == 0) {
        System.out.println("暂无学生信息。");
        return;
    }

    System.out.println("学生选课门数统计结果：");
    for (int i = 0; i < studentCount; i++) {
        Student student = students[i];
        int courseCount = 0;

        // 统计该学生的选课门数
        for (int j = 0; j < enrollmentCount; j++) {
            if (enrollments[j].getStudentId().equals(student.getStudentId())) {
                courseCount++;
            }
        }

        System.out.println((i + 1) + ". " + student.getName() +
                          "(" + student.getStudentId() + ")" +
                          " - 选课门数: " + courseCount);
    }
}

private static void analyzeGradeDistribution() {
    System.out.println("\n=== 课程成绩分布统计 ===");
    if (enrollmentCount == 0) {
        System.out.println("暂无选课记录。");
        return;
    }

    // 统计有成绩的记录数
    int gradedCount = 0;
    for (int i = 0; i < enrollmentCount; i++) {
        if (enrollments[i].getGrade() != null) {
            gradedCount++;
        }
    }

    if (gradedCount == 0) {
        System.out.println("暂无成绩记录。");
        return;
    }

    // 初始化各分数段计数器
    int[] gradeRanges = new int[5]; // 0:90-100, 1:80-89, 2:70-79, 3:60-69, 4:0-59

    // 统计各分数段人数
    for (int i = 0; i < enrollmentCount; i++) {
        Double grade = enrollments[i].getGrade();
        if (grade != null) {
            if (grade >= 90) {
                gradeRanges[0]++;
            } else if (grade >= 80) {
                gradeRanges[1]++;
            } else if (grade >= 70) {
                gradeRanges[2]++;
            } else if (grade >= 60) {
                gradeRanges[3]++;
            } else {
                gradeRanges[4]++;
            }
        }
    }

    System.out.println("成绩分布统计结果：");
    System.out.println("优秀(90-100分): " + gradeRanges[0] + "人");
    System.out.println("良好(80-89分):  " + gradeRanges[1] + "人");
    System.out.println("中等(70-79分):  " + gradeRanges[2] + "人");
    System.out.println("及格(60-69分):  " + gradeRanges[3] + "人");
    System.out.println("不及格(0-59分): " + gradeRanges[4] + "人");
    System.out.println("总成绩记录数: " + gradedCount + "条");
}

}
